<template>
    <view class="progress-box">
        <canvas class="progress-canvas" :id="canvasId" :canvas-id="canvasId" :style="{
            width: diameter + 'px',
            height: diameter + 'px'
        }"></canvas>
        <view class="progress-text">{{ currentPercentage }}%</view>
    </view>
</template>

<script>
export default {
    props: {
        percentage: { type: Number, default: 0 },
        diameter: { type: Number, default: 200 },
        lineWidth: { type: Number, default: 12 },
        canvasId: { type: String, default: 'progressCanvas' },
    },
    data() {
        return {
            currentPercentage: 0,
            ctx: null,
            systemInfo: null,
            realDiameter: 0,
            realLineWidth: 0
        }
    },
    mounted() {
        this.systemInfo = uni.getSystemInfoSync()
        this.$nextTick(() => {
            this.initCanvas()
            this.animateProgress()
        })
    },
    methods: {
        async initCanvas() {
            const dpr = this.systemInfo.pixelRatio || 1
            this.realDiameter = this.diameter * dpr
            this.realLineWidth = this.lineWidth * dpr

            // 创建Canvas上下文
            this.ctx = uni.createCanvasContext(this.canvasId, this)

            // App端特殊处理
            if (process.env.VUE_APP_PLATFORM === 'app-plus') {
                // 方式1：使用setTimeout等待Canvas渲染完成
                setTimeout(() => {
                    this.setCanvasSize()
                }, 100)
            } else {
                // 非App端使用常规方式
                this.setCanvasSize()
            }
        },

        setCanvasSize() {
            return new Promise((resolve) => {
                const query = uni.createSelectorQuery().in(this)
                query.select(`#${this.canvasId}`)
                    .fields({ node: true, size: true })
                    .exec(res => {
                        if (res[0] && res[0].node) {
                            const canvas = res[0].node
                            canvas.width = this.realDiameter
                            canvas.height = this.realDiameter
                            resolve(true)
                        } else {
                            // 备用方案：直接使用style尺寸
                            console.warn('无法获取Canvas节点，使用备用方案')
                            this.realDiameter = this.diameter
                            this.realLineWidth = this.lineWidth
                            resolve(false)
                        }
                    })
            })
        },

        drawBaseCircle() {
            const center = this.realDiameter / 2
            const radius = (this.realDiameter - this.realLineWidth) / 2

            this.ctx.setStrokeStyle('#E2E2E2')
            this.ctx.setLineWidth(this.realLineWidth)
            this.ctx.beginPath()
            this.ctx.arc(center, center, radius, 0, 2 * Math.PI)
            this.ctx.stroke()
        },

        drawProgress(percent) {
            const center = this.realDiameter / 2
            const radius = (this.realDiameter - this.realLineWidth) / 2

            this.ctx.clearRect(0, 0, this.realDiameter, this.realDiameter)
            this.drawBaseCircle()

            const gradient = this.ctx.createLinearGradient(
                0,
                center,
                0,
                this.realDiameter
            )
            gradient.addColorStop(0, '#1FEFC4')
            gradient.addColorStop(1, '#01BE8C')

            this.ctx.setStrokeStyle(gradient)
            this.ctx.setLineCap('round')
            this.ctx.beginPath()
            this.ctx.arc(
                center,
                center,
                radius,
                -Math.PI / 2,
                (2 * Math.PI * percent / 100) - Math.PI / 2
            )
            this.ctx.stroke()
            this.ctx.draw(true)
        },

        animateProgress() {
            const animate = () => {
                if (this.currentPercentage <= this.percentage) {
                    this.currentPercentage = Math.min(
                        this.currentPercentage + 1,
                        this.percentage
                    )
                    this.drawProgress(this.currentPercentage)
                    setTimeout(animate, 16)
                }
            }
            animate()
        }
    }
}
</script>

<style scoped>
.progress-box {
    position: relative;
    display: inline-flex;
    justify-content: center;
    align-items: center;
}

.progress-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 14px;
    color: #333;
    font-weight: bold;
}

.progress-canvas {
    display: block;
}
</style>